package crawler;

import java.net.URL;

public class Parser {
	private String rawData;

	public Parser() {
		rawData = null;
	}

	public ParsedStuff parse(String rawdata, URL url) {
		//System.out.println("Parser.parse");
		ParsedStuff parserStuff = new ParsedStuff(url);
		rawData = rawdata.toLowerCase();
		String aux = getInfoInsideLabel(rawData, "head");
		aux = getInfoInsideLabel(aux, "title");
		parserStuff.setHead(aux);

		aux = getInfoInsideLabel(rawData, "body");
		aux = takeLabelsAway(aux);
		parserStuff.setBody(aux);

		parserStuff.setMeta(null); // for first try
		getLinks(parserStuff);
		// <A HREF= "
		//System.out.println("Done with Parser.parse");
		return parserStuff;
	}

	private String takeLabelsAway(String body) {
		String saux = "";
		boolean inLabel = false;
		int i = 0;
		while (i < body.length()) {
			//System.out.println("Looping in Parser.takeLabelsAway");
			char caux = body.charAt(i);
			if (caux == '<')
				inLabel = true;
			if (caux == '>')
				inLabel = false;
			else if (!inLabel)
				saux += caux;
			i++;
		}
		return saux;
	}

	// public ParsedStuff parse

	private void getLinks(ParsedStuff parserStuff) {
		String toBeParsed = new String(rawData);
		while (true) {
			//System.out.println("Parser.getLinks looping");
			int start = toBeParsed.indexOf("<a href=");
			if (start != -1) {
				toBeParsed = toBeParsed.substring(start + 8);
				int urlStart = toBeParsed.indexOf('"');
				if (urlStart != -1) {
					toBeParsed = toBeParsed.substring(urlStart + 1);
					int end = toBeParsed.indexOf('"');

					if (end != -1) {
						String link = toBeParsed.substring(0, end);
						toBeParsed=toBeParsed.substring(end);
						if(!link.startsWith("mailto:"))parserStuff.addLinkToList(link);
						continue;
					}
				}
			}
			break;
		}
	}

	/*
	 * 
	 */
	private String getInfoInsideLabel(String source, String label) {
		int start = source.indexOf("<" + label + ">");
		start += (2 + label.length()); // we add the length of the label, for
										// example: <title> is
		int end = source.lastIndexOf("</" + label + ">");
		
		if(end>=source.length() || start<0)
			if(start>=0)
				return source.substring(start);
			else
				return source;
		else 
			return source.substring(start, end);
	}

}
